<template>
    <div class="commodityCloseAnAccount">
        <div class="content">
            <div class="address">
                <div class="address-message">
                    <p class="address-message-city">{{addressDefault?.remark}}</p>
                    <p class="address-message-nameAndPhone">
                        <span class="nameAndPhone-name">{{ addressDefault?.name }}</span>
                        <span class="nameAndPhone-phone">{{ addressDefault?.link }}</span>
                    </p>
                </div>
                <div class="address-edit" @click="GoAddressList()">
                    <Edit size="16" ></Edit>
                </div>
            </div>
            <div class="shop">
                <p class="shop-title">商品详情</p>
                <div class="shop-message" v-if="entryType == 1 || entryType == 3">
                    <div class="left">
                        <div class="shop-message-photo">
                            <Image :src="singleShop != '' ? singleShop.detailsImgs[0] : ''"></Image>
                        </div>
                        <div class="shop-message-content">
                            <p>{{ singleShop.name }}</p>
                            <p class="content-introduce">{{ singleShop.header }}</p>
                        </div>
                    </div>
                    <div class="shop-message-price">
                        <p class="content-unitPrice">
                            <span class="content-unitPrice-unit">{{ entryType == 3 ? '积分' : '¥' }}</span>
                            <span class="content-unitPrice-price">{{ singleShop.price }}</span>
                        </p>
                        <p class="price-amount">x 1</p>
                    </div>
                </div>
                <template v-else-if="entryType == 2">
                    <template v-for="(i, idx) in shopList" :key="idx">
                        <div class="shop-message" >
                            <div class="left">
                                <div class="shop-message-photo">
                                    <Image :src="i != '' ? i.produce_img[0] : ''"></Image>
                                </div>
                                <div class="shop-message-content">
                                    <p>{{ i.produce_name }}</p>
                                    <p class="content-introduce">{{ i.produce_header }}</p>
                                </div>
                            </div>
                            <div class="shop-message-price">
                                <p class="content-unitPrice">
                                    <span class="content-unitPrice-unit">¥</span>
                                    <span class="content-unitPrice-price">{{ i.produce_price * i.num  }}</span>
                                </p>
                                <p class="price-amount">x {{ i.num }}</p>
                            </div>
                        </div>
                    </template>
                </template>
                <!-- <div class="shop-remark">
                    <p>备注:</p>
                    <p>xxxxxx</p>
                </div> -->
                <div class="shop-sumTo">
                    <div class="shop-sumTo-message">
                        <p>共 {{ totalAmount }} 件商品，小计</p>
                        <p>{{ entryType == 3 ? '积分' : '¥' }} {{ totalPrice }}</p>
                    </div>
                    <div class="shop-sumTo-integralMessage" v-if="entryType == 3">
                        <p>可抵扣积分剩余：{{ integralSurplus }}</p>
                    </div>
                </div>
            </div>
            <div class="payType">
                <p>支付方式</p>
                <p v-if="entryType == 3">积分支付</p>
                <p v-else>微信支付</p>
            </div>
        </div>
        <div class="order-pay">
            <div class="order-pay-content">
                <div class="integral-message" v-if="entryType == 3">
                    <p>积分抵扣：{{ integralSurplus <= totalPrice ? 0 : totalPrice }}</p>
                </div>
                <div class="num-price">
                    <p>合计</p>
                    <p>¥</p>
                    <p>{{ totalPrice }}</p>
                </div>
                <nut-button 
                    type="info" 
                    class="pay-opera"
                    @click="PayOpera">支付</nut-button>
            </div>
        </div>
    </div>
  </template>
  
  <script>
  import { onBeforeMount, onMounted, onBeforeUnmount, reactive, toRefs } from 'vue';
  import './index.scss';
  import { 
    GetCommodityDetails, 
    GetPayMessag, 
    GetAddressList, 
    GetIntegralCommodityDetails,
    GetUserIntegral,
    IntegralPay } from '../utils/api.js';
  import api from '../utils/api.js';
  import { Edit, Cart ,Order,RectRight,Setting,Message } from '@nutui/icons-vue-taro';
  import { Image } from '@tarojs/components';
  import Taro from '@tarojs/taro'
  import currency from 'currency.js'
  import { eventCenter, getCurrentInstance } from '@tarojs/taro'
  export default {
    name: 'Index',
    components: {
        Edit,Cart,Order,RectRight,Setting,Message,Image
    },
    setup(){
        const state = reactive({
            entryType: Taro.getCurrentInstance().router?.params.entryType, // 进入类型 1. 商品详情 2.购物车*
            singleShop: '',
            shopList:[],
            addressDefault: {},
            integralSurplus: '0', // 剩余积分
            totalAmount: 1,
            totalPrice: 0,
        });
        const GetSingleCommodityConfig = async () => {
            const detailsRes = await GetCommodityDetails({
                id: Taro.getCurrentInstance().router?.params.commodityId
            });
            if(detailsRes.code == 200) {
                state.singleShop = detailsRes.data;
                state.totalPrice = Number(detailsRes.data.price);
                state.aa = detailsRes.data.detailsImgs[0];
            }
        }
        const GetSomeCommodityConfig = () => {
            state.shopList = JSON.parse(Taro.getCurrentInstance().router?.params.commodityList);
            state.totalPrice = Taro.getCurrentInstance().router?.params.totalPrice;
            state.totalAmount = Taro.getCurrentInstance().router?.params.totalAmount;
        }
        const GetIntegralCommodityConfig = async () => {
            const detailsRes = await GetIntegralCommodityDetails({
                id: Taro.getCurrentInstance().router?.params.commodityId
            });
            if(detailsRes.code == 200) {
                state.singleShop = detailsRes.data;
                state.totalPrice = Number(detailsRes.data.price);
                state.aa = detailsRes.data.detailsImgs[0];
            }
            
        }
        const GetDefAddress = async () => {
            let addressRes = await GetAddressList({});
            if(addressRes.code == 200) {
                state.addressDefault = addressRes.data.list.find((i) => i.isdef == 1);
            };
        }
        const GetIntegralSurplus = async () => {
            let integralRes = await GetUserIntegral({});
            if(integralRes.code == 200) {
                state.integralSurplus = integralRes.data.score;
            }
        }
        onBeforeMount(() => {
            const onShowEventId = Taro.getCurrentInstance().router.onShow
            // 监听
            eventCenter.on(onShowEventId, onShow)
        })
        onMounted(() => {})
        onBeforeUnmount(() => {
            const onShowEventId = Taro.getCurrentInstance().router.onShow
            // 卸载
            eventCenter.off(onShowEventId, onShow)
        })
        const onShow = () => {
            GetDefAddress();
            GetIntegralSurplus();
            switch(state.entryType){
                case "1": 
                    GetSingleCommodityConfig();
                    break;
                case "2": 
                    GetSomeCommodityConfig();
                    break;
                case "3": 
                    GetIntegralCommodityConfig();
                    break;
            }
        }
        const GoAddressList = () => {
            Taro.navigateTo({
                url: `/pages/address-list/index`
            })
        }
        // 支付
        const PayOpera = async () => {
            if(state.addressDefault?.id == undefined) {
                Taro.showToast({
                    title: '请选择地址信息在进行支付！',
                    icon: 'error',
                    duration: 1500
                })
                return;
            }
            let disposeList = []
            switch(state.entryType){
                case "1": 
                case "3": 
                    let obj = {
                        produce_id: state.singleShop.id,
                        num: 1,
                        price: state.singleShop.price
                    }
                    disposeList.push(obj)
                    break;
                case "2": 
                    disposeList = state.shopList.map((i,idx) => {
                        console.log(i, )
                        return {
                            produce_id: i.id,
                            num: i.num,
                            price: i.produce_price
                        }
                    })
                    break;
           
            }
            if(state.entryType == 3){
                if(state.integralSurplus <= state.totalPrice) {
                    Taro.showToast({
                        title: '你的积分不足以支付',
                        icon: 'none',
                        duration: 1500
                    })
                    return;
                }
                let integralReq = await IntegralPay({
                    list: JSON.stringify(disposeList),
                });
                if(integralReq.code == 200) {
                    Taro.showToast({
                        title: '支付成功',
                        icon: 'success',
                        duration: 1500
                    })
                    setTimeout(() => {
                        Taro.navigateTo({
                            url: `/pages/order-list/index`
                        })
                    },1500)
                } else {
                    Taro.showToast({
                        title: '支付失败',
                        icon: 'none',
                        duration: 1500
                    })
                }
                return;
            }
            const payRes = await GetPayMessag({
                list: JSON.stringify(disposeList),
                addressId: state.addressDefault.id
            });
            if(payRes.status == 200) {
                Taro.requestPayment({
                    timeStamp: payRes.timeStamp,
                    nonceStr: payRes.nonceStr,
                    package: payRes.package,
                    signType: payRes.signType,
                    paySign: payRes.paySign,
                    success: function (res) {
                        Taro.showToast({
                            title: '支付成功',
                            icon: 'success',
                            duration: 1500
                        })
                        setTimeout(() => {
                            Taro.navigateTo({
                                url: `/pages/order-list/index`
                            })
                        },0)
                    },
                    fail: function (res) {
                        Taro.showToast({
                            title: '支付失败',
                            icon: 'none',
                            duration: 1500
                        })
                        setTimeout(() => {
                            Taro.navigateTo({
                                url: `/pages/order-list/index`
                            })
                        },0)
                    }
                })
            }
        }
        return {
            GoAddressList,
            PayOpera,
            ...toRefs(state),
        }
    }
  }
  </script>
  
  